/**
 * Mockcat Server
 * @author Wangtd
 */
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');

const config = require('./config.js');
const util = require('./lib/util.js');
const mocker = require('./lib/mocker.js');
const router = require('./lib/router.js');

var app = express();

// blog
util.mkdirsSync(util.path(config.blogDir, 'images'));
util.mkdirsSync(util.path(config.blogDir, 'articles'));
util.writeFileSync(config.blogDir + '/blogs.json', JSON.stringify({
    categories: [],
    articles: []
}, null, 2));
app.use('/app/blog', express.static(config.blogDir));
// app
app.use('/app', express.static(util.paths('../app')));
// parameter
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ type: 'application/json', limit: '5mb' }));
// mock
app.use('/mock', router);
util.mkdirsSync(config.mockDir);
app.use('/', mocker.mock(config.mockDir));

// start http server
http.createServer(app).listen(config.port, '0.0.0.0', function(error) {
    if (error) {
        console.error(error);
    } else {
        console.log('Mockcat server is running at http://localhost:%d/', config.port);
    }
});
